<?php

namespace App\Models;

use Dcat\Admin\Models\Administrator;
use Illuminate\Database\Eloquent\Model;

// 业主(合同)模块
class Owner extends Model
{
    protected $fillable = [
        'cycle',
        'cycle_price',
        'cycle_unit',
        'deposit',
        'description',
        'create_admin_id',
        'update_admin_id',
        'able_id',
        'able_type',
        'started_at',
        'ended_at',
        'contract',
        'image',
        'ownerable_id',
        'ownerable_type',
        'config',
        'closed',
        'address',
        'will_close'
    ];

    protected $casts = [
        'address' => 'json',
        'started_at' => 'date',
        'ended_at' => 'date',
        'config' => 'json',
        'closed' => 'boolean',
        'contract' => 'array',
        'will_close' => 'boolean'
    ];

    const CYCLE_UNIT_YEAR = 2;
    const CYCLE_UNIT_MONTH = 0;
    const CYCLE_UNIT_DAY = 1;

    public static $cycleUnitMap = [
        self::CYCLE_UNIT_MONTH => '月',
        self::CYCLE_UNIT_YEAR => '年',
        self::CYCLE_UNIT_DAY => '日'
    ];

    const STATUS_CLOSE = 0;
    const STATUS_OPEN = 1;

    public static $statusMap = [
        self::STATUS_CLOSE => '合同关闭',
        self::STATUS_OPEN => '合同开启'
    ];

    const DEPOSIT_TYPE_RETURN = 'deposit_type_return';  // 返还状态
    const DEPOSIT_TYPE_PAWN = 'deposit_type_pawn';  // 抵押状态

    public static $depositTypeMap = [
        self::DEPOSIT_TYPE_RETURN => '返还状态',
        self::DEPOSIT_TYPE_PAWN => '抵押状态'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function createAdmin()
    {
        return $this->belongsTo(Administrator::class, 'create_admin_id');
    }

    public function updateAdmin()
    {
        return $this->belongsTo(Administrator::class, 'update_admin_id');
    }

    public function ownerable()
    {
        return $this->morphTo();
    }

    public function items()
    {
        return $this->hasMany(OwnerItem::class);
    }

    // 获取最新一期没有支付的流水
    public function firstNotPayItem()
    {
        return $this->hasOne(OwnerItem::class)->whereNull('pay_at')->orderBy('count', 'asc');
    }

    // 获取最后一期流水
    public function lastItem()
    {
        return $this->hasOne(OwnerItem::class)->orderBy('count', 'desc');
    }
}
